// pages/index/index.js
//连接数据库
const db = wx.cloud.database();
const forecast_table = db.collection('forecast_table');
const user_table = db.collection('user_table');
const forecastJoin_table = db.collection('forecastJoin_table');
//用全局变量
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //新用户通过分享来到首页
    forecastId: null,

    activeIndex: 0,
    activeName: '0',
    //用户积分数
    tag: [{
        name: '全部'
      },
      {
        name: '社会'
      },
      {
        name: '财经'
      },
      {
        name: '体育'
      },
      {
        name: '娱乐'
      },
      {
        name: '教育'
      },
      {
        name: '房产'
      },
      {
        name: '科技'
      },
      {
        name: '其他'
      }
    ],


    forecast: [],

    userList: null,

  },



  setTableIndex(e) {
    console.log(e.currentTarget.dataset.name);
    this.setData({
      activeIndex: e.currentTarget.dataset.id,

      activeName: e.currentTarget.dataset.name
    })
    console.log(this.data.activeName);
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log(options)
    if (options.id) {
      this.setData({
        forecastId: options.id
      })
    } else {
      this.setData({
        forecastId: null
      })
    }



    //获取用户id
    this.getOpenid().then(this.getInfo, this.getInfo)
    //获取用户头像和名称

    this.getForecast().then(this.changeTime)



  },

  //云函数获取用户id
  getOpenid() {
    //使用全局变量 声明一下
    var p = new Promise((resolve, reject) => {

      wx.cloud.callFunction({
        name: 'getOpenid',
        complete: res => {
          console.log(res)
          console.log('云函数获取到的openid: ', res.result.openid)

          app.globalData.openid = res.result.openid
          console.log(app.globalData.openid)
          resolve()
        }
      })



    })
    return p


  },
  //异步操作 resolve（） 一定要写到success 或者 if else什么的里面
  //不能直接放在函数最外面那层
  getInfo(e) {
    var p = new Promise((resolve, reject) => {


      console.log('id为' + app.globalData.openid)
      user_table.where({

        userId: app.globalData.openid
      }).get({
        success: (res) => {

          if (res.data.length == 0) {
            console.log('新用户')
            wx.showModal({
              title: '提示',
              content: '授权获取您的头像和名称',
              showCancel: false,
              success: (res) => {

                if (res.confirm) {
                  this.newGetInfo()

                  console.log('用户点击确定')
                }
              }
            })
            resolve()
          } else {
            console.log(res.data[0])

            this.setData({
              userList: res.data[0],
            })
            console.log(this.data.userList)

            if (this.data.userList.userName == '神秘预测小子') {
              wx.showModal({
                title: '提示',
                content: '授权获取您的头像和名称',
                showCancel: false,
                success: (res) => {

                  if (res.confirm) {
                    this.getInfoAgain()

                    console.log('用户点击确定')
                  }

                }
              })

            }

            if (this.data.forecastId) {
              wx.navigateTo({
                url: '../joinForecast/jornForecast?id=' + this.data.forecastId,
              })
            }
            resolve()

          }




        },
        fail(err) {
          console.log(err)
          resolve()

        }

      })



    })
    return p





  },
  //请求获取用户头像和昵称
  newGetInfo(e) {
    wx.getUserProfile({
      desc: '正在获取', //不写不弹提示框
      success: (res) => {
        console.log("获取成功:", res)
        this.setData({
          // console.log(res.userInfo)
          // console.log(res.userInfo.nickName)
          // console.log(res.userInfo.avatarUrl)
          ['userList.userId']: app.globalData.openid,
          ['userList.userName']: res.userInfo.nickName,
          ['userList.userNumber']: 100,
          ['userList.userPhoto']: res.userInfo.avatarUrl,
          ['userList.userStatu']: 0,
          ['userList.joinNumber']: 0,
          ['userList.successNumber']: 0,
        })
        user_table.add({
          data: {
            userId: app.globalData.openid,
            userName: this.data.userList.userName,
            userNumber: this.data.userList.userNumber,
            userStatu: this.data.userList.userStatu,
            joinNumber: this.data.userList.joinNumber,
            successNumber: this.data.userList.successNumber,
            userPhoto: this.data.userList.userPhoto,
          },
          success: res => {

            console.log('上传成功')
          }

        })

        if (this.data.forecastId) {
          wx.navigateTo({
            url: '../joinForecast/jornForecast?id=' + this.data.forecastId,
          })
        }

      },
      fail: (err) => {
        console.log('用户拒绝授权')
        this.setData({
          ['userList.userId']: app.globalData.openid,
          ['userList.userName']: '神秘预测小子',
          ['userList.userNumber']: 100,
          ['userList.userPhoto']: 'https://tse4-mm.cn.bing.net/th/id/OIP-C.ySKATe0Oi5hNgYR9JYBzDgAAAA?w=186&h=186&c=7&r=0&o=5&dpr=1.25&pid=1.7',
          ['userList.userStatu']: 0,
          ['userList.joinNumber']: 0,
          ['userList.successNumber']: 0,
        })
        console.log(this.data.userList)
        user_table.add({
          data: {
            userId: app.globalData.openid,
            userName: this.data.userList.userName,
            userNumber: this.data.userList.userNumber,
            userStatu: this.data.userList.userStatu,
            joinNumber: this.data.userList.joinNumber,
            successNumber: this.data.userList.successNumber,
            userPhoto: this.data.userList.userPhoto,
          },
          success: res => {

            console.log('上传成功')
          }

        })

        if (this.data.forecastId) {
          wx.navigateTo({
            url: '../joinForecast/jornForecast?id=' + this.data.forecastId,
          })
        }

      }

    })

  },

  //如果是之前拒绝获取头像的用户再次请求获取用户头像和昵称
  getInfoAgain(e) {
    wx.getUserProfile({
      desc: '正在获取', //不写不弹提示框
      success: (res) => {
        console.log("获取成功:", res)

        this.setData({
          ['userList.userName']: res.userInfo.nickName,
          ['userList.userPhoto']: res.userInfo.avatarUrl,

        })
        user_table.where({
          userId: app.globalData.openid
        }).update({
          data: {
            userName: this.data.userList.userName,
            userPhoto: this.data.userList.userPhoto,

          },
          success: res => {
            console.log('更新成功')
          },
          fail: err => {

            console.error('[数据库] [更新记录] 失败：', err)
          }
        })

        if (this.data.forecastId) {
          wx.navigateTo({
            url: '../joinForecast/jornForecast?id=' + this.data.forecastId,
          })
        }


      },
      fail: (err) => {
        console.log('用户拒绝授权')

        if (this.data.forecastId) {
          wx.navigateTo({
            url: '../joinForecast/jornForecast?id=' + this.data.forecastId,
          })

        }


      }
    })

  },
  //时间戳转化为时间
  changeTime(e) {
    console.log('第二步开始')


    for (let i = 0; i < this.data.forecast.length; i++) {


      //拿到的endDate是时间戳 Date型 转化为年月日 字符串型
      let date = this.data.forecast[i].endDate.toLocaleDateString().replace(/\//g, "-") + " " + this.data.forecast[i].endDate.toTimeString().substr(0, 6)

      date = date.replace('-', '年');
      date = date.replace('-', '月');
      date = date.replace(' ', '日');
      date = date.replace(':', '时');
      date = date.replace(':', '分');



      //改变对应index的某个属性值

      this.setData({
        ['forecast[' + i + '].endDate']: date,

      })


    }




  },
  //拿数据
  getForecast() {

    console.log('先拿forecast表数据 1')
    var p = new Promise((resolve, reject) => {
      //先拿forecast表数据 1

      forecast_table.orderBy('creatTime', 'desc').where({
        //审核状态为1 且按时间顺序取出
        examine: 1
      }).get({
        success: (res) => {
          console.log(res.data)
          this.setData({
            forecast: [...res.data],
          })
          resolve()
          console.log(this.data.forecast)
        },
        fail(err) {
          console.log(err)
          console.log('初次加入预测失败了')
        }

      })

    })
    return p

  },
  //到底了再拿一次数据 一次拿20条
  getAgain() {
    console.log('拿forecast表数据 1')
    var p = new Promise((resolve, reject) => {
      //先拿forecast表数据 1



      forecast_table.orderBy('creatTime', 'desc').skip(this.data.forecast.length).where({
        //审核状态为1 且按时间顺序取出
        examine: 1
      }).get({
        success: (res) => {
          console.log(res.data)

          this.setData({
            tempList: [...res.data],

          })
          resolve()
          console.log(this.data.tempList)

        },
        fail(err) {
          console.log(err)
          console.log('初次加入预测失败了')
        }

      })

    })
    return p

  },
  changeAgain() {
    console.log('第二步开始')
    console.log(this.data.tempList.length)

    let PromiseArr = []
    for (let i = 0; i < this.data.tempList.length; i++) {
      PromiseArr.push(new Promise((resolve, reject) => {


        //拿到的endDate是时间戳 Date型 转化为年月日 字符串型
        let date = this.data.tempList[i].endDate.toLocaleDateString().replace(/\//g, "-") + " " + this.data.tempList[i].endDate.toTimeString().substr(0, 6)
        date = date.replace('-', '年');
        date = date.replace('-', '月');
        date = date.replace(' ', '日');
        date = date.replace(':', '时');
        date = date.replace(':', '分');
        console.log(date)

        //改变对应index的某个属性值

        this.setData({
          ['tempList[' + i + '].endDate']: date,

        })
        console.log(this.data.tempList)
        resolve()

      }))
    }
    Promise.all(PromiseArr).then(res => {
      console.log('全部完成')
      this.concatList()

    })



  },
  concatList() {
    console.log('第三步')
    let oldList = this.data.forecast
    let tempList = this.data.tempList
    console.log(oldList)
    console.log(tempList)
    this.setData({
      forecast: oldList.concat(tempList)
    })
    console.log(this.data.forecast)
  },


  /**
   * 页面上拉触底 加载下一波
   */
  onReachBottom: function () {


    this.getAgain().then(this.changeAgain)



  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})